<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            :icon="Plus"
            size="mini"
            @click="handleAdd()"
            v-hasPermi="['kjy:application:add']"
        >
          新增专利
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            :icon="Delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:application:remove']"
        >
          删除
        </el-button>
      </el-col>
    </el-row>

    <el-table
        v-loading="loading"
        :header-row-style="{ height: '70px', color: 'black', 'font-size': '16px' }"
        :header-cell-style="{ 'background-color': '#f5f7fa' }"
        :row-style="{ height: '60px' }"
        :data="intellectualList"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="专利名称" align="center" prop="name" />
      <el-table-column label="企业名称" align="center" prop="enterpriseName" />
      <el-table-column label="专利类型" align="center" prop="type">
        <template #default="scope">
          {{ getPatentTypeName(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column label="附件" align="center" prop="certificate">
        <template #default="scope">
          <a
              v-if="scope.row.certificate !== null"
              :href="getFirstItem(scope.row.certificate)"
              target="_blank"
          >
            {{ getFirstItem(scope.row.certificate).split('/').pop() }}
          </a>
        </template>
      </el-table-column>

      <el-table-column label="专利号" align="center" prop="certificateNumber" />
      <el-table-column label="获得时间" align="center" prop="certificateDate" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" type="info">未审核</el-tag>
          <el-tag v-if="scope.row.status === 1" type="success">审核成功</el-tag>
          <el-tag v-if="scope.row.status === 2" type="danger">审核失败</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              size="mini"
              type="primary"
              :icon="Edit"
              link
              v-if="scope.row.status === 0"
              @click="handleUpdate(scope.row)"
          >
            修改
          </el-button>
          <el-button
              size="mini"
              type="danger"
              :icon="Delete"
              link
              v-if="scope.row.status === 0"
              @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
          <el-button
              size="mini"
              type="info"
              :icon="View"
              link
              v-if="scope.row.status === 1 || scope.row.status === 2"
              @click="handleView(scope.row)"
          >
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div
        :style="{
        padding: '15px',
        'background-color': '#fff',
        display: 'flex',
        'justify-content': 'end',
      }"
    >
      <el-pagination
          background
          :total="total"
          layout="prev, pager, next"
          v-model:page-size="queryParams.size"
          v-model:current-page="queryParams.current"
          @current-change="handlePageChange"
      />
    </div>

    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="专利名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入专利名称" :disabled="isView" />
        </el-form-item>
        <el-form-item label="企业名称" prop="enterpriseName">
          <el-input v-model="form.enterpriseName" placeholder="请输入企业名称" :disabled="isView" />
        </el-form-item>
        <el-form-item label="专利类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择专利类型" :disabled="isView">
            <el-option
                v-for="item in types"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专利编号" prop="certificateNumber">
          <el-input v-model="form.certificateNumber" placeholder="请输入专利编号" :disabled="isView" />
        </el-form-item>
        <el-form-item label="获取日期" prop="certificateDate">
          <el-date-picker
              v-model="form.certificateDate"
              type="date"
              placeholder="选择获取专利日期"
              :disabled="isView"
          />
        </el-form-item>
        <el-form-item label="上传附件" prop="certificate">
          <el-upload
              :headers="headers"
              multiple
              :accept="['doc', 'docx', 'pdf', 'png', 'jpg', 'jpeg']"
              :on-success="HandleSuccess"
              action="api/file/upload"
              :limit="3"
              :file-list="FileList"
              :disabled="isView"
          >
            <el-button size="small" type="primary" :disabled="isView">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">文件大小不超过5mb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="isView">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  getMyIntellectualProperty,
  getPatentType,
  addInfo,
  updateInfo,
  delInfo,
} from '@/api/my-patent';
import { getToken } from '@/utils/storage';
import { Delete, Plus, Edit, View } from '@element-plus/icons-vue';
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref('');
const open = ref(false);
const headers = ref({
  Authorization: getToken(),
});
const FileList = ref([]);
const queryParams = ref({
  current: 1,
  size: 10,
  enterpriseName: null,
});
const form = ref({
  id: null,
  name: '',
  enterpriseName: '',
  type: '', // 1 发明专利/ 2 实用新型/3 软著
  certificateNumber: '',
  certificate: '',
  certificateDate: '',
  publishTime: '',
  status: 0, // 添加状态字段，默认为0（未审核）
});
const rules = reactive({
  name: [{ required: true, message: '专利名称不能为空', trigger: 'blur' }],
  enterpriseName: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '专利类型不能为空', trigger: 'blur' }],
  certificateNumber: [{ required: true, message: '专利号不能为空', trigger: 'blur' }],
  certificateDate: [{ required: true, message: '获取日期不能为空', trigger: 'blur' }],
});
const intellectualList = ref([]);
const types = ref([]);
const enterprises = ref([]);
const selectedItem = ref(null);
const searchText = ref(null);
const isLoading = ref(false);
const isView = ref(false); // 控制查看模式

// 获取专利类型
const getPatentTypeData = async () => {
  try {
    const response = await getPatentType();
    types.value = response.data;
    console.log('专利类型数据:', types.value); // 调试信息
  } catch (error) {
    console.error('Failed to fetch patent types:', error);
  }
};

// 查询专利列表
const getList = async () => {
  loading.value = true;
  try {
    const response = await getMyIntellectualProperty(queryParams.value);
    intellectualList.value = response.data.records;
    total.value = response.data.total;
    queryParams.value.current = response.data.current;
  } finally {
    loading.value = false;
  }
};

// 获取第一个项
const getFirstItem = (item) => {
  if (item !== null && typeof item === 'string') {
    const items = item.split(',');
    return items.length > 0 ? items[0].trim() : item;
  }
  return item;
};

// 根据专利类型值获取类型名称
const getPatentTypeName = (typeValue) => {
  // 确保类型匹配，将typeValue转换为字符串进行比较
  const typeValueStr = String(typeValue);
  const typeItem = types.value.find(item => String(item.dictValue) === typeValueStr);
  return typeItem ? typeItem.dictLabel : typeValue;
};

// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
};

// 表单重置
const reset = () => {
  form.value = {
    id: null,
    name: '',
    enterpriseName: '',
    type: '',
    certificateNumber: '',
    certificate: '',
    certificateDate: '',
    publishTime: '',
    status: 0, // 重置状态字段
  };
  selectedItem.value = null;
  searchText.value = null;
  FileList.value = [];
  isView.value = false; // 重置查看模式
};

// 搜索功能
const handleQuery = () => {
  queryParams.value.current = 1; // 重置分页
  getList();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

// 添加按钮
const handleAdd = () => {
  reset();
  open.value = true;
  title.value = '添加知识产权';
};

// 修改按钮
const handleUpdate = (row) => {
  reset();
  // 使用扩展运算符创建副本，避免直接引用
  form.value = { ...row };
  // 确保专利类型的数据类型与字典匹配
  if (form.value.type !== undefined && form.value.type !== null) {
    form.value.type = String(form.value.type);
  }
  FileList.value = row.certificate ? [{ name: row.certificate, url: row.certificate }] : [];
  open.value = true;
  title.value = '修改知识产权';
  isView.value = false; // 设置为编辑模式
};

// 查看按钮
const handleView = (row) => {
  reset();
  // 使用扩展运算符创建副本，避免直接引用
  form.value = { ...row };
  // 确保专利类型的数据类型与字典匹配
  if (form.value.type !== undefined && form.value.type !== null) {
    form.value.type = String(form.value.type);
  }
  FileList.value = row.certificate ? [{ name: row.certificate, url: row.certificate }] : [];
  open.value = true;
  title.value = '查看知识产权';
  isView.value = true; // 设置为查看模式
};

// 提交按钮
const submitForm = () => {
  const isValid = validateForm();
  if (isValid) {
    form.value.publishTime = new Date().toISOString();
    if (form.value.id != null) {
      updateInfo(form.value)
          .then(() => {
            ElMessage.success('修改成功');
            open.value = false;
            getList();
          })
          .catch((error) => console.error('更新失败:', error));
    } else {
      addInfo(form.value)
          .then(() => {
            ElMessage.success('新增成功');
            open.value = false;
            getList();
          })
          .catch((error) => console.error('添加失败:', error));
    }
  }
};

// 表单验证
const validateForm = () => {
  // 检查必填字段是否已填写
  if (!form.value.name) {
    ElMessage.error('专利名称不能为空');
    return false;
  }
  if (!form.value.enterpriseName) {
    ElMessage.error('企业名称不能为空');
    return false;
  }
  if (!form.value.type) {
    ElMessage.error('专利类型不能为空');
    return false;
  }
  if (!form.value.certificateNumber) {
    ElMessage.error('专利号不能为空');
    return false;
  }
  if (!form.value.certificateDate) {
    ElMessage.error('获取日期不能为空');
    return false;
  }
  return true;
};

// 删除按钮
const handleDelete = (row) => {
  const idsToDelete = row.id || ids.value;
  ElMessageBox.confirm('是否确认删除选中数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(() => {
        delInfo(idsToDelete)
            .then(() => {
              getList();
              ElMessage.success('删除成功');
            })
            .catch((error) => console.error('删除失败:', error));
      })
      .catch(() => {
      });
};

// 分页变化
const handlePageChange = (currentPage) => {
  queryParams.value.current = currentPage;
  getList();
};

// 文件上传成功
const HandleSuccess = (response) => {
  form.value.certificate = response.data.url;
};

// 监听查询参数的变化，自动触发查询
watch(
    queryParams,
    () => {
      handleQuery();
    },
    {deep: true}
);

// 组件挂载时调用
onMounted(() => {
  getList();
  getPatentTypeData();
});
</script>

<style>
.app-container {
  padding: 20px;
  width: 100%;
  background-color: #fff;
}
</style>